import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import BooksMangement from '../components/BooksMangement.vue'
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Login',
      meta:{
        title:"登录"
      },
      component: Login,
    },
    {
      path: '/home',
      name: 'Home',
      meta:{
        title:"首页"
      },
      component: Home,
      children:[
        {
          path: '/books',
          name: 'books',
          meta:{
            title:"用户页"
          },
          component: BooksMangement,
        },
      ]
    },
  
  ],
})

//添加路由守卫（前置守卫）
router.beforeEach((to,from,next)=>{
  //判断本地存储中，是否有登录的标识，token令牌
  let islogin=localStorage.getItem('token')?true:false
  if(to.path==="/"){
    next()//继续放行
  }else if(islogin){
    next()
  }else{
    ElMessage({
      message: '警告：你没有登录,请登录',
      type: 'warning',
      })
    next({path:"/"})
  }
   
})
// 后置导航守卫：在页面跳转后自动执行其回调函数
router.afterEach((to, from) => {
  // 更新页面标题对跳转页面路由信息中的 title 属性值
  document.title = to.meta.title;
});

export default router
